#ifndef QUERYRESULT_H
#define QUERYRESULT_H
#include "TextQuery.h"

class QueryResult
{
    friend std::ostream& print(std::ostream&, const QueryResult&);
    // friend TextQuery;
private:
    std::string sought; // 查询单词
    std::shared_ptr<std::set<TextQuery::line_no>> lines; // 出现的行号
    std::shared_ptr<std::vector<std::string>> file; // 输入文件
public:
    QueryResult(std::string s,
                std::shared_ptr<std::set<TextQuery::line_no>> p,
                std::shared_ptr<std::vector<std::string>> f):
                sought(s), lines(p), file(f) { }
};

std::ostream& print(std::ostream & os, const QueryResult &qr)
{
    // 如果找到了单词，打印出现次数和所有出现的位置
    os << qr.sought << " occurs " << qr.lines->size() << " "
       << make_plural(qr.lines->size(), "time", "s") << std::endl;
    // 打印单词出现的每一行
    for(auto num : *qr.lines) // 对 set 中每个单词
    {
        // 避免行号从0开始给用户带来的困惑
        os << "\r(line " << num + 1 << ")" << *(qr.file->begin() + num) << std::endl;
    }
    return os;
}

std::string make_plural(std::size_t ctr, const std::string &word, const std::string &ending)
{
    return (ctr > 1)? word + ending : word;
}
#endif